package com.tsp_tux.demo.Util;

import lombok.Getter;
import lombok.Setter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 刘海生
 */

public class Lt {

    private final String fromURL;

    @Getter
    @Setter
    private String lt;
    @Getter
    @Setter
    private String cookies;

    public Lt(String fromURL) {
        this.fromURL = fromURL;
    }

    public void obtain() throws IOException {
        URLConnection connection = new URL(fromURL).openConnection();
        connection.connect();
        List<String> cookies = connection.getHeaderFields().get("Set-Cookie");
        StringBuilder cookieStringBuilder = new StringBuilder();
        for (String cookie : cookies) {
            Pattern pattern = Pattern.compile("[^=]+=[^;]+;");
            Matcher matcher = pattern.matcher(cookie);
            if (matcher.find()) {
                cookieStringBuilder.append(matcher.group());
                cookieStringBuilder.append(" ");
            }
        }
        cookieStringBuilder.delete(cookieStringBuilder.length() - 2, cookieStringBuilder.length());
        this.cookies = cookieStringBuilder.toString();
        InputStream inputStream = connection.getInputStream();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
            StringBuilder builder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line).append('\n');
            }
            Pattern pattern = Pattern.compile("<input type=\"hidden\" id=\"lt\" name=\"lt\" value=\"(.+?)\" />");
            Matcher matcher = pattern.matcher(builder.toString());
            if (matcher.find()) {
                lt = matcher.group(1);
            } else {
                throw new IOException("lt not found.");
            }
        }
    }
}
